package com.lihaozhe.service.impl;

import com.lihaozhe.service.AccessService;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.util.Collection;

/**
 * @author 李昊哲
 * @version 1.0
 * 2021/12/1 下午3:26
 */
@Service
public class AccessServiceImpl implements AccessService {
    @Override
    public Boolean hasPermission(HttpServletRequest request, Authentication authentication) {
        // 获取当前用户，可能是一个用户名，也可能是一个用户对象。
        Object principal = authentication.getPrincipal();
        if (principal instanceof UserDetails ) {
            UserDetails userDetails = (UserDetails) principal;
            // 获取用户的权限
            Collection<? extends GrantedAuthority> authorities = userDetails.getAuthorities();
            // 判断权限中是否有对应的URI
            return authorities.contains(new SimpleGrantedAuthority(request.getRequestURI()));
        }
        return false;
    }
}